package com.bangdream.michelia.view.fragment.main.my;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.application.MainApplication;
import com.bangdream.michelia.contract.UserContract;
import com.bangdream.michelia.entity.FinishedStateBean;
import com.bangdream.michelia.entity.RxEventBean;
import com.bangdream.michelia.entity.STSBean;
import com.bangdream.michelia.entity.UserBean;
import com.bangdream.michelia.entity.UserMsgBean;
import com.bangdream.michelia.presenter.UserPresenter;
import com.bangdream.michelia.presenter.base.BasePresenter;
import com.bangdream.michelia.tool.CircleImageView;
import com.bangdream.michelia.tool.FullyLinearLayoutManager;
import com.bangdream.michelia.tool.RoundCornerImageView;
import com.bangdream.michelia.tool.rejava.BaseObserverEntityNormalHttp;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.utils.GlideImageLoader;
import com.bangdream.michelia.utils.ImageLoadUtils;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.RxBus;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.currency.LoginActivity;
import com.bangdream.michelia.view.activity.currency.MainActivity;
import com.bangdream.michelia.view.activity.my.MyAboutUs;
import com.bangdream.michelia.view.activity.my.MyCertificate;
import com.bangdream.michelia.view.activity.my.MyExam;
import com.bangdream.michelia.view.activity.my.LearningRecords;
import com.bangdream.michelia.view.activity.my.MyCollection;
import com.bangdream.michelia.view.activity.my.MyMessage;
import com.bangdream.michelia.view.activity.currency.personal.PersonalCenterActivity;
import com.bangdream.michelia.view.adapter.MainItemMyListAdapter;
import com.bangdream.michelia.view.fragment.currency.BaseFragment;
import com.bangdream.michelia.view.fragment.currency.LazyLoadFragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 我的
 */
public class MyFragment extends LazyLoadFragment<UserContract.IUserView, UserPresenter<UserContract.IUserView>>
        implements View.OnClickListener, UserContract.IUserView, UserContract.IUserPicView, UserContract.IFinishState {
    private View view;
    private View statusBarHeight;
    private RelativeLayout titleBar;
    private RelativeLayout userInfoLayout;
    private RecyclerView recycleView;
    private FullyLinearLayoutManager linearLayoutManager;
    private MainItemMyListAdapter adapter;
    private TextView tvTitle, tvName, tvCompleteNumber, tvFractionNumber, tvCertificateNumber;
    ImageView ivGex;
    CircleImageView ivUser;
    private LinearLayout btnLearningRecords, btnMyCollection, btnMyExamination, btnMyMessage;
    private Button bt_exit;
    private List<ImageItem> images = new ArrayList<ImageItem>();
    private UserMsgBean userMsgBean;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_item_my, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        setListener();
        // 打开日志。
        OSSLog.enableLog();
        operateBus();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }


    @SuppressLint("CheckResult")
    public void operateBus() {
        disposable = RxBus.getInstance().toObservable().map(o -> (RxEventBean) o).subscribe(bean -> {
            if(bean.getCode()==0x02){
                mPresenter.getFinishstate();
            }
        });
    }

    @Override
    public UserPresenter<UserContract.IUserView> createPresenter() {
        return new UserPresenter<>();
    }

    @Override
    public void loadData() {
        AppCurrentUser user = AppCurrentUser.getInstance();
        mPresenter.getUserInfo(user.getUserInfo().getId(), user.getToken());
        mPresenter.getFinishstate();
    }

    private void setListener() {
        bt_exit.setOnClickListener(this);
        btnLearningRecords.setOnClickListener(this);
        btnMyCollection.setOnClickListener(this);
        btnMyExamination.setOnClickListener(this);
        btnMyMessage.setOnClickListener(this);
        adapter.setOnRecycleItemClick(new MainItemMyListAdapter.OnRecycleItemClick() {
            @Override
            public void onMyItemClick(int position) {
                if (position == 1) {
                    Intent intent = new Intent(getActivity(), PersonalCenterActivity.class);
                    intent.putExtra("userMsgBean", (Serializable) userMsgBean);
                    startActivity(intent);
                } else if (position == 2) {
                    startActivity(new Intent(getActivity(), MyAboutUs.class));

                } else if (position == 0) {
                    startActivity(new Intent(getActivity(), MyCertificate.class));
                }else if(position ==2){

                }
            }
        });
    }

    private void loginOut(){

        RetroFactory.getInstance().loginOut(AppCurrentUser.getInstance().getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseBody>() {

                    @Override
                    public void accept(ResponseBody responseBody) throws Exception {

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                    }
                });
    }

    private void initView() {
        if (MainApplication.getInstance().getWidth() > 0) {
            //填充用户信息的布局高度 需要根据屏幕宽高比 1:0.849..动态设置
            userInfoLayout = view.findViewById(R.id.userInfoLayout);
            ViewGroup.LayoutParams layoutParams = userInfoLayout.getLayoutParams();
            layoutParams.height = (int) Math.round(MainApplication.getInstance().getWidth() * 0.85);
            userInfoLayout.setLayoutParams(layoutParams);
        }
        tvName = view.findViewById(R.id.tvName);
        ivGex = view.findViewById(R.id.ivGex);
        ivUser = view.findViewById(R.id.ivUser);
        btnLearningRecords = view.findViewById(R.id.btnLearningRecords);
        btnMyCollection = view.findViewById(R.id.btnMyCollection);
        btnMyExamination = view.findViewById(R.id.btnMyExamination);
        bt_exit = view.findViewById(R.id.bt_exit);

        tvCompleteNumber = view.findViewById(R.id.tvCompleteNumber);
        tvFractionNumber = view.findViewById(R.id.tvFractionNumber);
        tvCertificateNumber = view.findViewById(R.id.tvCertificateNumber);

        btnMyMessage = view.findViewById(R.id.btnMyMessage);
        tvTitle = view.findViewById(R.id.tv_title);
        tvTitle.setText("个人中心");
        tvTitle.setTextColor(ContextCompat.getColor(mApp, R.color.text_on));
        //设置状态栏高度（与系统电量栏一样高的占位布局）
        statusBarHeight = view.findViewById(R.id.statusBarHeight);
        ViewGroup.LayoutParams layoutParams = statusBarHeight.getLayoutParams();
        layoutParams.height = MainActivity.statusBarHeight;
        statusBarHeight.setLayoutParams(layoutParams);
        titleBar = view.findViewById(R.id.titleBar);
        titleBar.setBackgroundColor(ContextCompat.getColor(mApp, R.color.transparent));
        recycleView = view.findViewById(R.id.recycleView);
        linearLayoutManager = new FullyLinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayout.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);
        adapter = new MainItemMyListAdapter(getActivity());
        recycleView.setAdapter(adapter);

        initImagePicker();
        ivUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, (Serializable) images);
                startActivityForResult(intent, 100);
            }
        });


    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
//        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == 100) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {

                    File file = new File(images.get(0).path);
                    Glide.with(getActivity())                             //配置上下文
                            .load(Uri.fromFile(file))      //设置图片路径(fix #8,文件名包含%符号 无法识别和显示)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存全尺寸
                            .into(ivUser);
                    upload();
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btnLearningRecords:
                intent = new Intent(getActivity(), LearningRecords.class);
                startActivity(intent);
                break;
            case R.id.btnMyCollection:
                intent = new Intent(getActivity(), MyCollection.class);
                startActivity(intent);
                break;
            case R.id.btnMyExamination:
                intent = new Intent(getActivity(), MyExam.class);
                startActivity(intent);
                break;
            case R.id.btnMyMessage:
                intent = new Intent(getActivity(), MyMessage.class);
                startActivity(intent);
                break;
            case R.id.bt_exit:
//                AppCurrentUser.getInstance().setToken("853a8dbf54574085a9a35cb22ef346b7");
                AppCurrentUser.getInstance().EndSign();
                loginOut();
                Intent intent2 = new Intent(getActivity(), LoginActivity.class);
                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                MainApplication.getContext().startActivity(intent2);
                getActivity().finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void setRegisterCode(boolean isSuccess, String stDescribe) {

    }

    @Override
    public void actionRegister(boolean isSuccess, String stDescribe) {

    }

    @Override
    public void actionLogin(boolean isSuccess, String stDescribe) {

    }

    @Override
    public void actionFindPassword(boolean isSuccess, String stDescribe) {

    }


    @Override
    public void setUserMsg(boolean isSuccess, UserMsgBean userMsgBean) {
        if (isSuccess) {
            this.userMsgBean = userMsgBean;
            tvName.setText(userMsgBean.getNickname());
            if (userMsgBean.getSex().equals("F")) {
                ivGex.setImageResource(R.mipmap.women_icon_my);
            } else {
                ivGex.setImageResource(R.mipmap.man_icon_my);
            }
            Glide.with(mApp)
                    .load(userMsgBean.getHead())
                    .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存全尺寸
                    .error(R.mipmap.header_moren)
                    .placeholder(R.mipmap.header_moren)
                    .into(ivUser);
        } else {
//            Toast.makeText(getContext(), "获取用户信息失败", Toast.LENGTH_SHORT).show();
        }

    }

    private void upload() {
        mPresenter.getSTS(AppCurrentUser.getInstance().getToken());
    }

    @Override
    public void setSTS(boolean isSuccess, final STSBean bean) {
        if (isSuccess && bean != null) {
            OSSStsTokenCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(bean.getAccessKeyId(), bean.getAccessKeySecret(), bean.getSecurityToken());
            OSS oss = new OSSClient(mApp, bean.getEndpointClean(), credentialProvider);
            final String randomUUID = UUID.randomUUID().toString().replace("-", "");


            PutObjectRequest put = new PutObjectRequest(bean.getBucket(), randomUUID, images.get(0).path);

            OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                    String url = "https://" + bean.getBucket() + "." + bean.getEndpointClean() + "/" + randomUUID;
                    mPresenter.uploadPic(url);
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                    Toast.makeText(getContext(), "头像更新失败", Toast.LENGTH_SHORT).show();
                    // 请求异常
                    if (clientExcepion != null) {
                        // 本地异常如网络异常等
                        clientExcepion.printStackTrace();
                    }
                    if (serviceException != null) {
                        // 服务异常
                        Log.e("ErrorCode", serviceException.getErrorCode());
                        Log.e("RequestId", serviceException.getRequestId());
                        Log.e("HostId", serviceException.getHostId());
                        Log.e("RawMessage", serviceException.getRawMessage());
                    }
                }
            });


        }

    }

    @Override
    public void setUrlMsg(boolean isSuccess) {

        if (isSuccess) {
            ToastUtil.showShortToast(getActivity(), "上传头像成功");
        }
    }

    @Override
    public void setFinishState(boolean isSuccess, FinishedStateBean bean) {
        if (isSuccess && bean!=null) {
            tvCompleteNumber.setText(transNum(bean.getCourse_finished()) + "门");
            tvFractionNumber.setText(transNum(bean.getExam_finished()) + "个");
            tvCertificateNumber.setText(transNum(bean.getCert_obtained()) + "门");
        }

    }


    private int transNum(List<String> list) {
        if (list != null) {
            list.removeAll(Collections.singleton(""));
            return list.size();
        } else {
            return 0;
        }
    }
}
